package com.heatup.apt.api.controller;

import com.alibaba.druid.util.*;
import com.heatup.apt.api.controller.pay.util.*;
import com.heatup.apt.api.service.*;
import com.heatup.apt.common.constants.*;
import com.heatup.apt.common.util.*;
import com.heatup.apt.model.api.*;
import com.heatup.apt.model.order.*;
import com.heatup.apt.model.user.*;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.*;
import javax.servlet.http.*;
import java.io.*;
import java.math.*;
import java.util.*;

/**
 * 微信支付控制器
 * <P>File name : WeChatPayController.java</P>
 * <P>Date : 2016年8月24日</P>
 */
@RequestMapping(value = "/pay/wechat")
@Controller
public class WeChatPayController extends BaseController {

	public static final Logger log = LoggerFactory.getLogger(WeChatPayController.class);

	@Resource
	private WeChatPayService weChatPayService;

	@Resource
	private UserStoreService userStoreService;
	@Resource
	private UserService userService;
	
	@Autowired
    private TSysPresaleTeamService tSysPresaleTeamService;
	
	/**
	 * 创建支付订单 WeChatPayController.createPayOrder()<BR>
	 * <P>Date : 2016年8月26日</P>
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/createPayOrder", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String createPayOrder(HttpServletRequest request) {
		ApiResultModel apiResultModel = new ApiResultModel();
		String callback = RequestTools.RequestString(request, "callback", "");
		try {
			String payAmount = RequestTools.RequestString(request, "payAmount", "");
			String orderType = RequestTools.RequestString(request, "orderType", "");
			String serviceId = RequestTools.RequestString(request, "serviceId", "");
			String personCount = RequestTools.RequestString(request, "personCount", "1");
			Integer storeId = RequestTools.RequestInt(request, "storeId", 0);
			String startTime = RequestTools.RequestString(request, "startTime", "");
			String endTime = RequestTools.RequestString(request, "endTime", "");
			int duration = RequestTools.RequestInt(request, "duration", 0);
			int courseCount = RequestTools.RequestInt(request, "courseCount", 1);
			Integer couponDetailId = RequestTools.RequestInt(request, "couponDetailId", 0);
			Integer payType =  RequestTools.RequestInt(request, "payType", 1);// 1 表示微信支付 2 表示个人储值账户 3 表示企业储值卡账户 4：微信+个人储值卡混合支付
			String weixinAmt = RequestTools.RequestString(request, "weixinAmt", "");// 表示微信支付金额
			String consumeAmt = RequestTools.RequestString(request, "consumeAmt", "");// 表示储值卡支付金额
			//绑定常去门店
			Integer favStoreId = RequestTools.RequestInt(request, "favStoreId", 0);// 表示储值卡支付金额
//			Long companyStaffId =  RequestTools.RequestLong(request, "companyStaffId", 0);//企业员工ID
			Integer productId = RequestTools.RequestInt(request, "productId", 0);// add jxy
			String companyAmt = RequestTools.RequestString(request, "companyAmt", ""); // 企业储值卡支付
			String courseAttr = RequestTools.RequestString(request, "courseAttr", ""); 
			Integer coachId	  = RequestTools.RequestInt(request, "coachId", 0);
			Integer mealCount = RequestTools.RequestInt(request,"mealCount",0);
			Integer mealCouponCount = RequestTools.RequestInt(request,"mealCouponCount",0);
			Integer dataDictId = RequestTools.RequestInt(request,"dataDictId",0);
			String phone = RequestTools.RequestString(request, "phone", "");
			Integer orderId = RequestTools.RequestInt(request, "orderId", 0);
			String userName = RequestTools.RequestString(request, "userName", ""); 
			String code = RequestTools.RequestString(request, "code", "");

			// 绑定的常去门店
			if(favStoreId != 0) {
				userStoreService.update(favStoreId, this.getUserId());
			}
			
			
			// 会籍开单用户支付的时候需要校验手机号码
			// 如果手机号码不存在就绑定
			UserInfo userInfo = this.getUserInfo();
			if(orderId > 0 && userInfo != null && StringUtils.isEmpty(userInfo.getMobile())) {
				Object syscode = this.getSession(SESSION_KEY_CHECK_CODE);
                Object lastSend = this.getSession(SESSION_KEY_CHECK_CODE_LAST_SEND);
                
				Map<String,Object> checkMap = userService.userUpdateMobile(userInfo.getId(), code, String.valueOf(syscode), lastSend, phone, userName);
				boolean checkStatus = (boolean) checkMap.get("isCheckStatus");
				if(!checkStatus) {
					apiResultModel.setRet(ApiResultModel.RET_ERROR);
					apiResultModel.setMsg((String)checkMap.get("msg"));
					return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
				}
			}
			
			
			String priceTypeCode = RequestTools.RequestString(request,"priceTypeCode","1");
			if(StringUtils.isEmpty(payAmount) || (new BigDecimal(payAmount)).compareTo(BigDecimal.ZERO) == 0){
	        	payAmount = "0";
	        }
			if(StringUtils.isEmpty(weixinAmt) || (new BigDecimal(weixinAmt)).compareTo(BigDecimal.ZERO) == 0){
				weixinAmt = "0";
	        }
			if(StringUtils.isEmpty(consumeAmt) || (new BigDecimal(consumeAmt)).compareTo(BigDecimal.ZERO) == 0){
				consumeAmt = "0";
	        }
			if(StringUtils.isEmpty(companyAmt) || (new BigDecimal(companyAmt)).compareTo(BigDecimal.ZERO) == 0){
				companyAmt = "0";
	        }
			
			
			apiResultModel = weChatPayService.createPayOrderRestructure(getUserInfo(), payAmount, orderType, serviceId,
					personCount, request.getRemoteAddr(), storeId, startTime, endTime, duration, courseCount,
					couponDetailId, payType, weixinAmt.trim(), consumeAmt.trim(), productId.intValue(), priceTypeCode,
					companyAmt, courseAttr, coachId,mealCount,mealCouponCount, dataDictId, orderId);
			

		} catch (Exception e) {
			e.printStackTrace();
			log.error("创建支付订单出错--->" + e.toString() + e.getCause(),e);
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setMsg("围裙健身支付失败:" + e.toString() + e.getCause());
		}

		// 更新一下缓存
		UserInfo userInfo = userService.selectById(getUserId());
		setUserInfo(userInfo);

		apiResultModel.setLogined(isLogined());
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}
	
	/**
	 * 修改订单付款状态为付款中，前提是订单付款状态为未付款
	 * WeChatPayController.updatePayStatus()<BR>
	 * <P>Date : 2016年10月24日 </P>
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updatePayStatus", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String updatePayStatus(HttpServletRequest request) {
		ApiResultModel apiResultModel = new ApiResultModel();
		try {
			String orderId = RequestTools.RequestString(request, "orderId", "");
			apiResultModel = weChatPayService.updatePayStatus(orderId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("修改订单付款状态出错 --->" + e.toString() + e.getCause(),e);
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setMsg("修改订单付款状态失败:" + e.toString() + e.getCause());
		}
		String callback = RequestTools.RequestString(request, "callback", "");
		apiResultModel.setLogined(isLogined());
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}

	/**
	 * 微信支付成功回调地址 WeChatPayController.weChatPayCallback()<BR>
	 * <P>Date : 2016年8月24日</P>
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/weChatPayCallback", method = { RequestMethod.POST, RequestMethod.GET })
	public void weChatPayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("UTF-8");
		BufferedReader buff = null;
		StringBuffer str = null;
		str = new StringBuffer();
		String s = null;
		buff = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
		while ((s = buff.readLine()) != null) {
			str.append(s);
		}
		String xmlBody = str.toString();
		Map map = XMLUtil.doXMLParse(xmlBody);
		SortedMap<String, String> retMap = new TreeMap<String, String>();
		if ("SUCCESS".equals(map.get("return_code"))) {
			String out_trade_no = (String) map.get("out_trade_no");
			String transaction_id = (String) map.get("transaction_id");
			try {
				boolean updateStatus = weChatPayService.updatePayOrder(out_trade_no, transaction_id);
				log.info("微信支付回调处理 结果  ===> " + updateStatus);
			} catch (Exception e) {
				e.printStackTrace();
				log.error("微信支付成功回调出错 ----->>> " + e.toString() + e.getCause(), e);
			}
			retMap.put("return_code", "SUCCESS");
		} else {
			retMap.put("return_code", "FAIL");
		}

		// 更新一下缓存
		UserInfo userInfo = userService.selectById(getUserId());
		setUserInfo(userInfo);

		response.getWriter().write(XMLUtil.toXml(retMap));
	}

	@ResponseBody
	@RequestMapping(value = ("/updateOrder1"))
	public String updateOrder(HttpServletRequest request, HttpServletResponse response) {
		ApiResultModel<Map<String, String>> apiResultModel = new ApiResultModel<Map<String, String>>(isLogined());
		String callback = "";
		UserDiscount ud = weChatPayService.getUserDiscount(1);
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}
	
	/**
	 *  测试updateOrder的方法
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = ("/updateOrderTest"))
	public String updateOrderNew(HttpServletRequest request, HttpServletResponse response){
		String out_trade_no = RequestTools.RequestString(request, "trade_no", "");
		String transaction_id = RequestTools.RequestString(request, "transaction", "");
		weChatPayService.updatePayOrder(out_trade_no, transaction_id);
		return "";
	}
	
	/**
	 * 写前端操作日志记录信息
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/createPayLog")
	public String createPayLog(HttpServletRequest request, HttpServletResponse response){
		ApiResultModel apiResultModel = new ApiResultModel();
		String logs = RequestTools.RequestString(request, "logs", null);
		String serviceType = RequestTools.RequestString(request, "serviceType", null);
		String callback =  RequestTools.RequestString(request, "callback", "");
		try {
			int userId = this.getUserId();
			weChatPayService.createPayLogs(userId, serviceType, logs);
			apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
			apiResultModel.setMsg("");
		} catch (Exception ex) {
			apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
			apiResultModel.setMsg("");
			ex.printStackTrace();
			log.error("createPayLog error:",ex);
		}
		apiResultModel.setLogined(isLogined());
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}
	
	/**
	 * 线下购买餐
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/payMealOrder" , method = {RequestMethod.GET , RequestMethod.POST})
	public String testCretaeMealOrder(HttpServletRequest request, HttpServletResponse response) {
		ApiResultModel apiResultModel = new ApiResultModel();
		String callback =  RequestTools.RequestString(request, "callback", "");
		Integer userId = RequestTools.RequestInt(request, "userId", 0);
		Integer mealCount = RequestTools.RequestInt(request, "mealCount", 1);
		String payAmount = RequestTools.RequestString(request, "payAmount", "0");
		Integer convertDateCount = RequestTools.RequestInt(request, "convertDateCount", 0);
		Integer payType = RequestTools.RequestInt(request, "payType", 2);
		if(!isLogined()) {
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setMsg("未登录请先登录");
			return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
		}
		
		try {
			apiResultModel = weChatPayService.createPayMealOrder(this.getUserInfo(), userId,
					OrderContants.OrderType.meal.getType(), String.valueOf(payType),
					new BigDecimal(payAmount).setScale(2, BigDecimal.ROUND_HALF_UP), mealCount, null, convertDateCount);
		}catch(NumberFormatException e) {
			log.error("API payMealOrder 购买餐支付失败 ：" + e.toString() + e.getCause(), e);
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setMsg("围裙健身支付失败：请输入正确的支付金额");
		} catch (Exception e) {
			log.error("API payMealOrder 购买餐支付失败 ："+e.toString()+e.getCause(),e);
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setMsg("围裙健身支付失败："+e.getMessage());
		}
		
		apiResultModel.setLogined(this.isLogined());
		
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}
	
	
	/**
	 * 预售年卡订单 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/create_presale_card_order" , method = RequestMethod.POST )
	public String createPresaleCardOrder(HttpServletRequest request, HttpServletResponse response,@RequestBody   PresaleCardPayOrderApiModel presaleCardPayOrderApiModel) {
		String callback = RequestTools.RequestString(request, "callback", "");
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		UserInfo userInfo = this.getUserInfo();
		// 判断登陆
        if(userInfo == null) {
        	 apiResultModel.setRet(ApiResultModel.RET_ERROR);
             apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
             apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
             return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel),callback);
        }
        // 先判断权限
        boolean hasPresale = tSysPresaleTeamService.checkPresalTeamUser(userInfo.getId(), userInfo.getMobile());
        if(!hasPresale) {
        	apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg(ErrorCodeConstants.Code.NOT_HAS_PERMISSIONS.getMessage());
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.NOT_HAS_PERMISSIONS.getCode());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel),callback);
        }
		try {
			presaleCardPayOrderApiModel.setOpendOrderUserId(userInfo.getId());
			apiResultModel = weChatPayService.createPayPresaleCardOrder(presaleCardPayOrderApiModel, userInfo);
		} catch (Exception e) {
			log.error("presaleOpendOrder| error:"+e.toString()+e.getCause(),e);
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage());
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
		}
		apiResultModel.setLogined(this.isLogined());
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel),callback);
	}

	/**
	 *@Author: timo
	 *@Date: 2018/3/26 09:40
	 *@Description:
	 * 创建私教订单
	 * 主要用于私教开单
	 */
	@ResponseBody
	@RequestMapping(value = "/create_private_course_order" , method = RequestMethod.POST )
	public String createPrivateCourseOrder(HttpServletRequest request, @RequestBody PresalePrivateCourseOrderModel orderModel) {
		String callback = RequestTools.RequestString(request, "callback", "");
		ApiResultModel<Object> model = new ApiResultModel<>();
		UserInfo userInfo = this.getUserInfo();
		// 判断登陆
		if(userInfo == null) {
			model.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
			model.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
			model.setRet(ApiResultModel.RET_ERROR);
			return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(model),callback);
		}

		try {
			model = weChatPayService.createPayPrivateCourseOrder(orderModel,userInfo);
		} catch (Exception e) {
			// TODO: handle exception
			log.error("presaleOpendOrder| error:"+e.toString()+e.getCause(),e);
			model.setRet(ApiResultModel.RET_ERROR);
			model.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage());
			model.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
		}
		model.setLogined(this.isLogined());
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(model),callback);
	}

}